package frame.ddd.lossmodel;

import frame.ddd.lossmodel.basic.*;

import java.util.Collection;
import java.util.Date;

/**
 * desc     : 事务的管理是在ItemManger这一层完成的，ItemManager实现具体的业务逻辑。除了常见的和CRUD有关的简单逻辑之外，
 *          这里还有一个placeBid的逻辑，即项目的竞标
 * dateTime : 2020/8/6 18:42
 *
 * @author cww
 */

public class ItemManager {
    private ItemDao itemDao;
    private ItemState state;
    public void setItemDao(ItemDao itemDao) { this.itemDao = itemDao;}
    public Bid loadItemById(Long id) {
        itemDao.loadItemById(id);
        return  null;
    }
    public Collection listAllItems() {
        return  itemDao.findAll();
    }
    public Bid placeBid(Item item, User bidder, MonetaryAmount bidAmount,
                        Bid currentMaxBid, Bid currentMinBid) throws BusinessException {
        if (currentMaxBid != null && currentMaxBid.getAmount().compareTo(bidAmount) > 0) {
            throw new BusinessException("Bid too low.");
        }

        // Auction is active
        if ( !state.equals(ItemState.ACTIVE) )
            throw new BusinessException("Auction is not active yet.");

        // Auction still valid
        if ( item.getEndDate().before( new Date() ) )
            throw new BusinessException("Can't place new bid, auction already ended.");

        // Create new Bid
        Bid newBid = new Bid(bidAmount, item, bidder);

        // Place bid for this Item
        item.getBids().add(newBid);
        itemDao.update(item);      //   调用DAO完成持久化操作
        return newBid;
    }
}
